<template>
    <div class="setting">
        <RiskMarquee v-if="SHOW_MARQUEE" class="marquee" :textArr="textArr" />

        <el-tabs type="card" v-model="editableTabsValue" closable @tab-remove="removeTab">
            <el-tab-pane name="条目设置">
                <span slot="label"> <i class="yh-tiaomuzhibiaopeizhi1"></i>条目设置 </span>
                <div class="setting-list">
                    <RiskControlFSCINDA v-if="WEB_DOCKING === 'FSCINDA'" :tabsIndex="tabsIndex" @refresh="refresh" />
                    <RiskControl v-else :tabsIndex="tabsIndex" @refresh="refresh" />
                </div>
            </el-tab-pane>
            <el-tab-pane name="条目复核">
                <span slot="label"> <i class="yh-check"></i>条目复核 </span>
                <div class="setting-fh">
                    <keep-alive>
                        <RiskControlCheck :editableTabsValue="editableTabsValue"></RiskControlCheck>
                    </keep-alive>
                </div>
            </el-tab-pane>
            <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
                <ItemControlDetail
                    :itemData="item"
                    @opne-table="getInstruct"
                    @getPageType="getPageType"
                    :key="item.name"
                    v-if="
                        item.type == 'look' ||
                            item.type == 'add' ||
                            item.type == 'edit' ||
                            item.type == 'copy' ||
                            item.type == 'editCheck' ||
                            item.type == 'lookCheck' ||
                            item.type == 'check-look' ||
                            item.type == 'editCheckSetting'
                    "
                ></ItemControlDetail>
                <CustomSetting :itemData="item" @close-custom="openCustom" v-if="item.type == 'customize'"></CustomSetting>
                <ItemUpdateRecord :itemData="item" @close-custom="openCustom" v-if="item.type == 'record'"></ItemUpdateRecord>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import RiskControl from './components/item-setting/risk-control.vue';
import RiskControlCheck from './components/item-setting/risk-control-check.vue';
import ItemControlDetail from './components/item-setting/item-control-detail.vue';
import CustomSetting from './components/item-setting/custom-setting.vue';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import ItemUpdateRecord from './components/item-setting/item-update-record.vue';
import RiskMarquee from '@/common/components/risk-marquee.vue';
import { getUser } from '@/utils/user-util';
import { getConfigItem, GunDataGzip, StringToBase64 } from '@/utils/tools';
import RiskControlFSCINDA from './components/item-setting/risk-control-fscinda.vue';
import { DELETE_CACHE, GET_CACHE } from '@/utils/diction-const-util';

@Component({
    name: 'ItemSetting',
    components: {
        RiskControl,
        RiskControlCheck,
        ItemControlDetail,
        CustomSetting,
        ItemUpdateRecord,
        RiskMarquee,
        RiskControlFSCINDA,
    },
})
export default class ItemSetting extends mixins(RiskEmitter) {
    SHOW_MARQUEE: boolean = getConfigItem('SHOW_MARQUEE');
    BASE_URL_WS = getConfigItem('BASE_URL_WS');
    WEB_DOCKING = getConfigItem('WEB_DOCKING');

    editableTabsValue: string = '条目设置';
    editableTabs: any = [];
    tabsIndex: any = 0;
    pageTypes: any = ''; // 表格操作按钮打开界面类型
    TimeSendMessage: any = null;
    webSocket: any = null;
    textArr: string[] = [
        // '张成1 复核通过 YH001 entryNameentryNameentryNameentryNameentryNameentryName',
        // '张成2 复核拒绝 YH001 entryName',
        // '张成3 修改条目 YH001 entryNameentryNameentryNameentryName',
        // '张成4 新增条目 YH001 entryName',
    ];
    created() {
        // 跳转参数处理
        if (GET_CACHE('JumpParams')) {
            this.changComponets({ type: 'look', value: GET_CACHE('JumpParams').entryCode }); // 页面个性代码
            DELETE_CACHE('JumpParams'); // 处理完参数后必须清除, 如果需要做持久化, 请另外缓存
            window.addEventListener('storage', this.jumpEventMethod);
        } else {
            window.addEventListener('storage', this.jumpEventMethod);
        }
        this.$on('addTables', this.changComponets);
    }

    mounted() {
        if (this.SHOW_MARQUEE) {
            this.initWebsocket();
        }
    }

    beforeDestroy() {
        if (this.TimeSendMessage) {
            clearInterval(this.TimeSendMessage);
            this.TimeSendMessage = null;
        }
        this.webSocket.onopen = null;
        this.webSocket.onmessage = null;
        this.webSocket.onclose = null;
        this.webSocket.onerror = null;
        this.webSocket.close();
        this.webSocket = null;

        window.removeEventListener('storage', this.jumpEventMethod);
    }

    jumpEventMethod(event) {
        if (event.storageArea === sessionStorage && event.key === 'JumpParams') {
            if (GET_CACHE('JumpParams') && GET_CACHE('JumpParams').for && GET_CACHE('JumpParams').for === '投资风险设置') {
                console.log('缓存被修改了！', event.key, event.newValue, event);
                this.changComponets({ type: 'look', value: GET_CACHE('JumpParams').entryCode }); // 页面个性代码
                DELETE_CACHE('JumpParams'); // 处理完参数后必须清除, 如果需要做持久化, 请另外缓存
            }
        }
    }
    // 监控子组件发送的命令
    changComponets(datas: any) {
        const data: any = {};
        data.type = datas.type;
        data.content = datas.value;
        if (datas.type === 'add') {
            data.title = '新增条目';
            data.name = '新增条目';
        } else if (datas.type == 'addUFX') {
            data.title = '新增O32条目';
            data.name = '新增O32条目';
            data.type = 'add';
            data.isO32Item = true;
        } else if (datas.type === 'edit') {
            data.title = '编辑：' + datas.value;
            data.name = '编辑：' + datas.value;
        } else if (datas.type === 'look') {
            data.title = '查看：' + datas.value;
            data.name = '查看：' + datas.value;
        } else if (datas.type === 'copy') {
            data.title = '复制：' + datas.value;
            data.name = '复制：' + datas.value;
        } else if (datas.type === 'check-look') {
            data.title = '查看：' + datas.value.entryCode;
            data.name = '查看：' + datas.value.entryCode;
        } else if (datas.type === 'customize') {
            data.title = '自定义设置：' + datas.value;
            data.name = '自定义设置：' + datas.value;
        } else if (datas.type === 'record') {
            data.title = '修改记录：' + datas.value;
            data.name = '修改记录：' + datas.value;
        } else if (datas.type == 'editCheck') {
            data.title = '复核编辑：' + datas.value.entryCode;
            data.name = '复核编辑：' + datas.value.entryCode;
        } else if (datas.type == 'editCheckSetting') {
            data.title = '复核编辑：' + datas.value.entryCode;
            data.name = '复核编辑：' + datas.value.entryCode;
        } else if (datas.type == 'lookCheck') {
            data.title = '复核查看：' + datas.value.entryCode;
            data.name = '复核查看：' + datas.value.entryCode;
        }
        const item = this.editableTabs.find((item: any) => item.name === data.name);
        if (!item) {
            this.addTab(data);
        } else {
            this.editableTabsValue = data.name;
        }
    }
    getPageType(val) {
        this.pageTypes = val;
    }
    // 传过来的关闭页面
    getInstruct(data: any, type: any) {
        this.tabsIndex = this.tabsIndex + 1;
        this.removeTab(data, type);
    }

    // 关闭tabs
    removeTab(targetName: string, type?: string) {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
            tabs.forEach((tab: any, index: any) => {
                if (tab.name === targetName) {
                    let nextTab = tabs[index + 1] || tabs[index - 1];
                    if (nextTab) {
                        activeName = nextTab.name;
                    }
                }
            });
        }
        let str = targetName;
        str = str.substr(0, str.indexOf('：'));
        // 默认跳转到条目设置
        if (str == '复核查看' || (str == '复核编辑' && this.pageTypes != 'editCheckSetting')) {
            this.editableTabsValue = '条目复核';
        } else {
            this.editableTabsValue = '条目设置';
        }
        // this.editableTabs = null;
        this.editableTabs = tabs.filter((tab: any) => tab.name !== targetName);
    }

    // 新增tabs
    addTab(targetName: any) {
        if (this.editableTabs.length > 4) {
            // this.yh_message_warn('打开了过多的标签页, 请先关闭空闲的标签页!');
            console.log('打开了过多的标签页, 请先关闭空闲的标签页!');
            this.editableTabs.shift();
        }
        this.editableTabs.push(targetName);
        this.editableTabsValue = targetName.name;
    }

    // 关闭自定义
    openCustom(val: any) {
        this.editableTabsValue = '条目设置';
        this.removeTab(val);
    }

    // 初始化websocket
    private initWebsocket(): void {
        let Authentication = getUser().sessionId;

        const urlH = '/entry';
        let webSocket = new WebSocket(this.BASE_URL_WS + urlH + '/socket/' + StringToBase64(Authentication));
        webSocket.onopen = e => {
            console.log('----------WS连接成功----------');
        };

        webSocket.onmessage = e => {
            let process = JSON.parse(e.data);
            this.packageTextArr(process);
        };

        webSocket.onclose = e => {
            console.log('----------WS连接断开----------');
            console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
            console.log(e);
        };

        this.webSocket = webSocket;
        // 每隔10分发送一次消息
        this.TimeSendMessage = setInterval(() => {
            try {
                webSocket.send('条目更新提醒-发送WEBSOCKET心跳消息');
            } catch (e) {}
        }, 1000 * 60 * 10);
    }

    private packageTextArr(data: any[]): void {
        // 增量
        // if (data && data.length) {
        //     let textArr = [...this.textArr];
        //     data.forEach((item, index) => {
        //         // ${item.modifyUser} ${item.modityType}
        //         textArr.splice(index, 1, `${item.entryCode} ${item.entryName}`);
        //     });
        //     this.textArr = textArr;
        // }
        // 全量覆盖
        if (data && data.length) {
            let textArr = [];
            data.forEach((item, index) => {
                // ${item.modifyUser} ${item.modityType}
                textArr.splice(index, 1, `${item.entryCode} ${item.entryName}`);
            });
            this.textArr = textArr;
        }
    }

    private refresh(): void {
        if (this.webSocket) {
            this.webSocket.close();
            this.textArr = [];
            this.$nextTick(() => {
                this.initWebsocket();
            });
        }
    }
}
</script>
<style lang="scss" scoped>
.setting {
    height: 100%;
    padding-top: 10px;
    min-width: 1200px;
}
.setting /deep/ .el-tabs .el-tabs__nav .el-tabs__item {
    line-height: 34px;
    padding: 0 25px;
}

.setting /deep/ .el-tabs .el-tabs__nav .el-tabs__item span {
    border-right: 0px solid #fff;
}

.setting /deep/ .el-tabs .el-tabs__nav .el-tabs__item:nth-child(1) .el-icon-close {
    display: none;
}

.setting /deep/ .el-tabs .el-tabs__nav .el-tabs__item:nth-child(2) .el-icon-close {
    display: none;
}

.marquee {
    position: absolute;
    right: 0;
    top: 10px;
    z-index: 0;
    width: 550px;
}
/deep/ .el-tabs {
    height: 100%;
    .el-tabs__header {
        min-width: auto;
        z-index: 111;
    }
    .el-tabs__content {
        height: calc(100% - 40px);
        .el-tab-pane {
            height: 100%;
        }
    }
}
/deep/ .el-card {
    height: 100%;
    .el-card__body {
        height: 100%;
    }
}
</style>
